package com.haixee.parkdemo.common.filter;

import com.haixee.parkdemo.common.context.WebContextHolder;
import com.haixee.parkdemo.common.response.ExceptionUtil;
import com.haixee.parkdemo.common.response.RequestUtil;
import com.haixee.parkdemo.common.response.ResResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 捕获 Filter 中的异常, 如 token
 *
 * @author GUIFENG GUO
 * 2020/3/22 9:24
 */
@Slf4j
@WebFilter(filterName = "ExceptionFilter", urlPatterns = {"/*"})
@Order(value = Integer.MAX_VALUE - 300)
@Configuration
public class ExceptionFilter implements Filter {

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        try {
            filterChain.doFilter(servletRequest, servletResponse);
        } catch (Exception ex) {
            ResResult commonRes = ExceptionUtil.getExceptionResponse(ex);
            HttpServletResponse response = (HttpServletResponse) servletResponse;
            RequestUtil.writeResult(response, commonRes.getStatus(), commonRes);
            WebContextHolder.setResponseCode(commonRes.getCode());
            WebContextHolder.setResponseMsg(commonRes.getMsg());
        }
    }

}
